package cn.darkhorse.mesadmin.task;

import cn.darkhorse.alarm.pojo.AlarmRecordInfo;
import cn.darkhorse.alarm.service.AlarmRecordInfoService;
import cn.darkhorse.common.config.TaskConfig;
import cn.darkhorse.device.iot.constant.IotConstant;
import cn.darkhorse.device.pojo.MesDevice;
import cn.darkhorse.device.service.MesDeviceService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 太平港设备状态更新
 */
@Component("deviceTask")
public class MesDeviceTask {

    @Resource
    private MesDeviceService deviceService;
    @Resource
    private AlarmRecordInfoService alarmRecordInfoService;
    @Resource
    private RedisCache redisCache;

    /**
     * 定时监测设备状态
     */
//    @Scheduled(cron = "0/15 * * * * *")
    public void checkDeviceStatus(){
        if(!TaskConfig.isFlag()){
            return;
        }
        System.out.println("开始监测设备状态");
        List<MesDevice> list = deviceService.list(new LambdaQueryWrapper<MesDevice>());
//                .eq(MesDevice::getIsAcquisitionDevice, 1))
//        List<MesDevice> children = list.stream().filter(device -> device.getParentId() != null).collect(Collectors.toList());
//        list = list.stream().filter(device-> device.getParentId()==null).collect(Collectors.toList());
//        Map<Long, List<MesDevice>> childrenMap = children.stream().collect(Collectors.groupingBy(MesDevice::getParentId));
        // 监测每个设备的在线离线状态
        LocalDateTime now = LocalDateTime.now();
        String sql = "select device_id, add_date from mqtt_live_data";
        List<Map<String, Object>> liveMaps = SqlRunner.db().selectList(sql);
        Map<Object, Map<String, Object>> collect = liveMaps.stream().collect(Collectors.toMap(map -> map.get("device_id"), map -> map));
        list.forEach(device-> {
            try {
                MesDevice updateDevice = new MesDevice();
                updateDevice.setId(device.getId());

                String fieldName = "add_date";
                String tableName = device.getHistoryTableName();
                if (StringUtils.isEmpty(tableName)) {
                    return;
                }

                List<String> idList = new ArrayList<>();
//                List<MesDevice> mesDevices = childrenMap.get(device.getId());
//                if (mesDevices != null && !mesDevices.isEmpty()) {
//                    mesDevices.forEach(mesDevice -> {
//                        idList.add(mesDevice.getGatewayDeviceId());
//                    });
//                }
                idList.add(device.getGatewayDeviceId());

//                String sql = "select top 1 " + fieldName + " from " + tableName + " order by " + fieldName + " desc";
//                String sql = "select device_id, add_date from mqtt_live_data where device_id = {0}";
//                Map<String, Object> map = SqlRunner.db().selectOne(sql, device.getGatewayDeviceId());
//                String sql = "select device_id, add_date from mqtt_live_data where device_id in {0}";
                List<Map<String, Object>> maps = new ArrayList<>();

                for (String s : idList) {
                    System.out.println(s);
                    if (collect.containsKey(s)){
                        System.out.println(s);
                        System.out.println(collect);
                        maps.add(collect.get(s));
                    }
                }
                for (Map<String, Object> map : maps) {

                    // 子设备逻辑修改 有任何一台子设备在线即显示在线
                    String str = map.get(fieldName).toString().replace("T", " ");
                    if (str.length() < 19) {
                        str = str + ":00";
                    }
                    LocalDateTime createdAt = LocalDateTime.parse(str.substring(0, 19),
                            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    if (Duration.between(createdAt, now).getSeconds() > IotConstant.DEVICE_ONLINE_TIMEOUT) {
                        System.out.println(map+":离线");
                        // 大于60秒没有上传，任务设备已经离线
                        updateDevice.setDeviceOnline(false);
                    } else {
                        System.out.println(map+":离线");
                        // 任意一台子设备在线,即返回在线,跳出循环
                        updateDevice.setDeviceOnline(true);
                        break;
                    }
                }


                // 判断设备是否有报警信息
                List<AlarmRecordInfo> alarmRecordInfos = alarmRecordInfoService.list(new LambdaQueryWrapper<AlarmRecordInfo>()
                        .eq(AlarmRecordInfo::getDeviceId, device.getId())
                        .eq(AlarmRecordInfo::getAlarmStatus, 0)
                        .orderByDesc(AlarmRecordInfo::getId));

                if (!alarmRecordInfos.isEmpty()) {
                    updateDevice.setDeviceRunningStatus(2);
                }else {
                    updateDevice.setDeviceRunningStatus(0);
                }
                if (!device.getDeviceOnline()){
                    String realDataKey = IotConstant.CACHE_MQTT_DATA_REAL_DATA + device.getGatewayDeviceId();
                    redisCache.deleteObject(realDataKey);
                }

                deviceService.updateById(updateDevice);

            }catch (Exception e) {
                e.printStackTrace();
            }

        });

        // 监测每个设备的
        System.out.println("结束监测设备状态" + "供处理数据：" + list.size() + "条");
    }
}
